using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using XNACamera;

namespace TP3
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Model depInfo, perso;
        Texture2D viseur, viseur2, burst1, burst2, burst3;
        Matrix matWorld, mModMove;
        CameraSubjective cam, cam2;
        Viewport viewport1, viewport2;
        Vector3 posCam,posModele,rotModele;
        bool visee, tir=false;
        Ray P1ray, P2ray;
        int P1pv = 100, P2pv = 100;
        float sensi=0.05f;
        Song sndPan;


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 1200;
            graphics.PreferredBackBufferHeight = 400;
        }

        private void DrawModel(Model m, Camera c, Matrix transform)
        {
            Matrix[] transforms = new Matrix[m.Bones.Count];
            m.CopyAbsoluteBoneTransformsTo(transforms);
            foreach (ModelMesh mesh in m.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.View = c.View;
                    effect.Projection = c.Projection;
                    effect.World = transforms[mesh.ParentBone.Index] * transform;
                    effect.LightingEnabled = true;
                    effect.DirectionalLight0.Enabled=true;
                    effect.DirectionalLight0.Direction = new Vector3(0,-1,0);
                    effect.DirectionalLight0.DiffuseColor = new Vector3(255, 255, 255);
                    effect.DirectionalLight0.SpecularColor = new Vector3(255, 255, 255);
                    effect.EmissiveColor = new Vector3(255, 255, 255);
                    effect.SpecularColor = new Vector3(255, 255, 255);
                    effect.SpecularPower = 64;
                }
                mesh.Draw();
            }
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            graphics.PreferredBackBufferWidth = graphics.GraphicsDevice.DisplayMode.Width;
            graphics.PreferredBackBufferHeight = graphics.GraphicsDevice.DisplayMode.Height;
            graphics.ToggleFullScreen();
            graphics.PreferredBackBufferWidth = 1200;
            graphics.PreferredBackBufferHeight = 400;
            graphics.ToggleFullScreen();
            matWorld = Matrix.Identity;
            posCam = new Vector3(0,50,-100);
            posModele = new Vector3();
            rotModele = new Vector3();
            cam = new CameraSubjective(this, posCam);
            cam2 = new CameraSubjective(this, posCam);
            viewport1 = GraphicsDevice.Viewport;
            viewport2 = GraphicsDevice.Viewport;
            viewport1.Width = viewport1.Width/2;
            viewport2.Width = viewport2.Width/2;
            viewport2.X = viewport1.Width;
            cam.Aspect = 4.0f/3.0f;
            cam2.Aspect = 4.0f/3.0f;
            visee = false;
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            depInfo = Content.Load<Model>("niveau400");
            perso = Content.Load<Model>("SuperMan");
            viseur = Content.Load<Texture2D>("visee1");
            viseur2 = Content.Load<Texture2D>("visee2");
            burst1 = Content.Load<Texture2D>("burst1");
            burst2 = Content.Load<Texture2D>("burst2");
            burst3 = Content.Load<Texture2D>("burst3");
            sndPan = Content.Load<Song>("pan");
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {

            GamePadState etatBoutons = GamePad.GetState(PlayerIndex.One);
            GamePadThumbSticks etatSticks = etatBoutons.ThumbSticks;

            if (etatBoutons.Buttons.Back == ButtonState.Pressed)
                this.Exit();
            if (etatBoutons.Buttons.A == ButtonState.Pressed)
                graphics.ToggleFullScreen();

            if (etatBoutons.IsButtonUp(Buttons.LeftStick))
            {
                cam.Avance(etatSticks.Left.Y * 4);
                cam.Lateral(etatSticks.Left.X * 4);
            }

            if (etatBoutons.IsButtonUp(Buttons.RightStick))
            {
                cam.HautBas += etatSticks.Right.Y * sensi;
                cam.GaucheDroite -= etatSticks.Right.X * sensi;
                
            }

            if (etatBoutons.IsButtonDown(Buttons.LeftTrigger))
                cam.AngleFov = MathHelper.Pi / 16;
            else
                cam.AngleFov = MathHelper.PiOver4;

            KeyboardState kbState = Keyboard.GetState();
            kbState.GetPressedKeys();

            if(kbState.IsKeyDown(Keys.Escape))
                this.Exit();

            if (kbState.IsKeyDown(Keys.Z)){
                cam2.Avance(4);
                mModMove = Matrix.CreateTranslation(cam2.Position);
            }

            if (kbState.IsKeyDown(Keys.S))
            {
                cam2.Avance(-4);
                mModMove = Matrix.CreateTranslation(cam2.Position);
            }

            if (kbState.IsKeyDown(Keys.Q))
            {
                cam2.Lateral(-4);
                mModMove = Matrix.CreateTranslation(cam2.Position);
            }

            if (kbState.IsKeyDown(Keys.D))
            {
                cam2.Lateral(4);
                mModMove = Matrix.CreateTranslation(cam2.Position);
            }
            int i = 0; 
            if (kbState.IsKeyDown(Keys.Left))
            {
                cam2.GaucheDroite += sensi;
                mModMove += Matrix.CreateRotationY(sensi);
                
            }

            if (kbState.IsKeyDown(Keys.Right))
            {
                cam2.GaucheDroite -= sensi;
                mModMove -= Matrix.CreateRotationY(sensi);
            }

            if (kbState.IsKeyDown(Keys.Up))
            {
                cam2.HautBas += sensi;
            }

            if (kbState.IsKeyDown(Keys.Down))
            {
                cam2.HautBas -= sensi;
            }

            if (kbState.IsKeyDown(Keys.LeftShift))
            {
                visee = true;
                cam2.AngleFov = MathHelper.Pi / 8;
                sensi = 0.025f;
            }
            else
            {
                visee = false;
                cam2.AngleFov = MathHelper.PiOver4;
                sensi = 0.05f;
            }

            if(kbState.IsKeyDown(Keys.Space)){
                tir = true;
                P2ray = new Ray(cam2.Position, cam2.Cible);
                if (P2ray.Intersects(new BoundingBox(cam.Position + new Vector3(-100, -100, -100), cam.Position + new Vector3(100, 100, 100))) != null)
                {
                    P1pv -= 100;
                }
            }
                
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.WhiteSmoke);
            //mModMove = Matrix.CreateTranslation(cam.Position);
            GraphicsDevice.Viewport = viewport1;
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            DrawModel(depInfo, cam, matWorld);
            DrawModel(perso, cam, mModMove);

            spriteBatch.Begin();
                if(visee == true){
                    spriteBatch.Draw(viseur, new Rectangle(0, 0, 600, 400), Color.White);
                    tir = false;
                }
                if (tir==true){
                    spriteBatch.Draw(burst1, new Rectangle(0, 0, 600, 400), Color.White);
                    spriteBatch.Draw(burst2, new Rectangle(0, 0, 600, 400), Color.White);
                    spriteBatch.Draw(burst3, new Rectangle(0, 0, 600, 400), Color.White);
                }
            spriteBatch.End();

            GraphicsDevice.Viewport = viewport2;
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            DrawModel(depInfo,cam2, matWorld);
            DrawModel(perso, cam2, mModMove);

            spriteBatch.Begin();
                if (visee == true)
                {
                    spriteBatch.Draw(viseur2, new Rectangle(0, 0, 600, 400), Color.White);
                }
                else
                {
                    spriteBatch.Draw(viseur, new Rectangle(0, 0, 600, 400), Color.White);
                }

                if (tir == true)
                {
                    Random rnd = new Random();

                    int i=rnd.Next(0,2);
                    if (i == 0)
                    {
                        spriteBatch.Draw(burst1, new Rectangle(0, 0, 600, 400), Color.White);
                    }
                    else if (i == 1)
                    {
                        spriteBatch.Draw(burst2, new Rectangle(0, 0, 600, 400), Color.White);
                    }
                    else if (i == 2)
                    {
                        spriteBatch.Draw(burst3, new Rectangle(0, 0, 600, 400), Color.White);
                    }
               
                    MediaPlayer.Play(sndPan);
                    //spriteBatch.Draw(var, new Rectangle(0, 0, 600, 400), Color.White);
                    tir = false;
                }
            spriteBatch.End();
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }
    }
}
